package cn.id68.www.http.callback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/3/21.
 */

public abstract class FileCallBack extends Callback<File> {

    /**
     * 目标文件存储的文件夹路径
     */
    private String destFileDir;

    private String destFileName;

    public FileCallBack(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    @Override
    public File parseNetworkResponse(Response response, int id) throws Exception {
        return null;
    }

    public File saveFile(Response response,final int id) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0;
            File dir = new File(destFileDir);
            if (!dir.exists()){
                dir.mkdirs();
            }
            File file = new File(dir,destFileName);
            fos = new FileOutputStream(file);

            while ((len = is.read(buf)) != -1){
                sum += len;
                fos.write(buf,0,len);
                final long finalSum = sum;

            }
            fos.flush();
            return file;
        }finally {
            response.body().close();
            try {
                if(fos != null)fos.close();
            }catch (IOException e){

            }
        }
    }

}
